class  Counter {
    public  int count = 0;
    public void add() {
        //随后调用add方法，又尝试对counter加锁
        //但counter已经被加锁了，如果再次尝试对counter加锁，就会出现阻塞等待
        synchronized (this){
            count++;
        }
    }
}

public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                //首先执行到这里，对counter加锁成功
                synchronized (counter){
                    counter.add();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (counter){
                    counter.add();
                }
            }
        });

        t.start();
        t2.start();
        t.join();
        t2.join();
        System.out.println(counter.count);
    }
}
